package com.framework.common.mongodb.utils;

import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.mapping.*;
import java.util.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: ywb
 * \* Date: 2021/11/19
 * \* Time: 16:59
 * \* Description:
 * \
 */
public class SortModelUtils {
    public static Sort.Direction getMongodbDirection(final int x) {
        switch (x) {
            case 0: {
                return Sort.Direction.ASC;
            }
            case 1: {
                return Sort.Direction.DESC;
            }
            default: {
                return null;
            }
        }
    }

    public static Sort getMongodbSort(final Integer[] sort, final String[] fields, final Class cls) {
        final List<Sort.Order> orders = new ArrayList<Sort.Order>();
        for (int i = 0; i < fields.length; ++i) {
            java.lang.reflect.Field field = null;
            try {
                field = cls.getDeclaredField(fields[i]);
            }
            catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            catch (SecurityException e2) {
                e2.printStackTrace();
            }
            final Field f = field.getAnnotation(Field.class);
            final Sort.Direction d = getMongodbDirection(sort[i]);
            orders.add(new Sort.Order(d, f.value()));
        }
        return Sort.by(orders);
    }

}
